package com.tcs.util.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import java.util.concurrent.locks.ReentrantLock;

/**
 * spring 容器工具<br>
 *
 * 容器类升级为SpringIocUtils
 * @see com.tcs.util.spring.SpringIocUtils
 * @author wangbo
 */
public class SpringConfigTool {

	private static ApplicationContext context = null;

	private SpringConfigTool() {};

	public static void setApplicationContext(ApplicationContext applicationContext) {
		context = applicationContext;
	}

	/**
	 * 获取静态变量中的ApplicationContext.
	 */
	public static ApplicationContext getApplicationContext() {
		return context;
	}

	/**
	 * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
	 * @param beanName
	 * @return
	 * @throws BeansException
	 */
	public static Object getBean(String beanName) throws BeansException {
		Object resultObj = null;
		try {
			resultObj = context.getBean(beanName);
			return resultObj;
		} catch (BeansException e) {
			throw e;
		}
	}
	
	/**
	 * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
	 */
	public static <T> T getBean(Class<T> requiredType) {
		T t = null;
		try {
			t = context.getBean(requiredType);
			return t;
		} catch (BeansException e) {
			throw e;
		}
	}
 
	/**
	 * 清除SpringContextHolder中的ApplicationContext为Null.
	 */
	public static void clearHolder() {
		context = null;
	}

}